import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../layout/index.vue'

Vue.use(VueRouter)

export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    hidden: true,
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/',
    redirect: 'home',
    component: Layout,
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('../views/home/index.vue'),
        meta: {
          title: '首页',
          icon: 'home'
        }
      },
      {
        path: '/analysis',
        name: 'Analysis',
        hidden: true,
        component: () => import('../views/home/components/analysis/index.vue'),
        meta: {
          title: '数据分析',
          icon: 'analysis',
          activeMenu: '/home'
        }
      }
    ]
  },
  {
    path: '/user',
    component: Layout,
    hidden: true,
    redirect: 'noRedirect',
    children: [
      {
        path: 'profile',
        component: () => import('@/views/system/profile/index'),
        name: 'Profile',
        meta: {
          title: '个人中心',
          icon: 'user',
          activeMenu: '/home'
        }
      }
    ]
  },
  {
    path: '/404',
    component: () => import('../views/system/error/404/index.vue'),
    hidden: true,
    meta: {
      title: '404 Not Found'
    }
  },
  {
    path: '/401',
    component: () => import('../views/system/error/401/index.vue'),
    hidden: true
  }
]

// 获取原型对象push函数
const originalPush = VueRouter.prototype.push
// 获取原型对象replace函数
const originalReplace = VueRouter.prototype.replace

/**
 * 修改原型对象中的push函数
 *
 * @param {*} location 当前要跳转路径的对象
 * @returns
 */
VueRouter.prototype.push = function push (location) {
  // this指向当前VueRouter的实例对象
  return originalPush.call(this, location).catch(err => err)
}

/**
 * 修改原型对象中的replace函数
 *
 * @param {*} location 当前要跳转路径的对象
 * @returns
 */
VueRouter.prototype.replace = function replace (location) {
  return originalReplace.call(this, location).catch(err => err)
}

const createRouter = () => new VueRouter({
  mode: 'history',
  // 路由切换时回到最顶端
  scrollBehavior: () => ({ y: 0 }),
  base: process.env.BASE_URL,
  routes: constantRoutes
})

// 新建路由
const router = createRouter()
// 重置路由函数 export
export function resetRouter () {
  const newRouter = createRouter()
  // 替换成新的空路由
  router.matcher = newRouter.matcher
}

export default router
